package com.example.mybatis.dao.impl;

import com.example.mybatis.dao.IUserDAO;
import com.example.mybatis.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDAOImpl implements IUserDAO
{
    SqlSessionFactory sqlSessionFactory;

    public UserDAOImpl(SqlSessionFactory sqlSessionFactory)
    {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public User queryUserById(int id)
    {
//        4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        5. 执行SqlSession对象执行查询，获取结果User
        User user = (User)sqlSession.selectOne("queryUserById",2);
//        6. 打印结果
        System.out.println(user);
//        7. 释放资源
        sqlSession.close();

        return user;
    }

    @Override
    public List<User> queryUserByUsername1(String name)
    {
        //        4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        5. 执行SqlSession对象执行查询，获取结果User
        List<User> users = sqlSession.selectList("queryUserByUsername","%张%");
//        6. 打印结果
        for(Object u:users) {
            System.out.println(u);
        }
        //        7. 释放资源
        sqlSession.close();

        return users;
    }

    @Override
    public List<User> queryUserByUsername2(String name)
    {
        //        4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        5. 执行SqlSession对象执行查询，获取结果User
        List<User> users = sqlSession.selectList("queryUserByUsername2","张");
//        6. 打印结果
        for(Object u:users) {
            System.out.println(u);
        }
        //        7. 释放资源
        sqlSession.close();

        return users;
    }

    @Override
    public int saveUser(User user)
    {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int result = sqlSession.insert("saveUser",user);
        sqlSession.commit();
        sqlSession.close();

        return result;
    }

    @Override
    public int deleteById(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int result = sqlSession.delete("deleteById",id);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int updateUserById(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int result = sqlSession.update("updateById",user);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }
}
